package com.tiantian.common.utils;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.tiantian.common.core.page.PageDomain;
import com.tiantian.common.core.page.TableSupport;
import com.tiantian.common.exception.BusinessException;
import com.tiantian.common.utils.sql.SqlUtil;

/**
 * 分页工具类
 *
 * @author ruoyi
 */
public class PageUtils extends PageHelper {
    /**
     * 设置请求分页数据
     */
    public static void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        String field = pageDomain.getField();
        String order = pageDomain.getOrder();
        // 防止爬虫
        if (pageSize > 20) {
            throw new BusinessException("参数不正确");
        }
        Boolean reasonable = pageDomain.getReasonable();
        PageHelper.startPage(pageNum, pageSize, SqlUtil.escapeOrderBySql(getOrderBy(field, order))).setReasonable(reasonable);
    }

    private static String getOrderBy(String orderByColumn, String sort) {
        if (StringUtils.isEmpty(orderByColumn)) {
            return "";
        }
        // 默认降序
        if (StringUtils.isEmpty(sort)) sort = "desc";
        // 驼峰转下划线
        return StrUtil.toUnderlineCase(orderByColumn) + " " + sort;
    }


    /**
     * 清理分页的线程变量
     */
    public static void clearPage() {
        PageHelper.clearPage();
    }
}
